<template>
  <div>
    <el-card style="height: 80px;">
  <el-form :inline="true" :model="userAddressDTO" ref="ruleForm" class="demo-form-inline">
    <el-form-item label="用户Id" prop="userId">
      <el-input style="width: 150px" v-model="userAddressDTO.userId" placeholder="用户Id"></el-input>
    </el-form-item>
    <el-form-item label="姓名" prop="recipientName">
      <el-input style="width: 150px" v-model="userAddressDTO.recipientName" placeholder="姓名">
      </el-input>
    </el-form-item>
    <el-form-item label="地址" prop="addressDetail">
      <el-input style="width: 150px" v-model="userAddressDTO.addressDetail" placeholder="地址">
      </el-input>
    </el-form-item>
    <el-form-item label="注册时间" prop="createdAt1">
      <el-date-picker style="width: 150px" v-model="userAddressDTO.createdAt1" type="date" placeholder="选择日期"></el-date-picker>
    </el-form-item>_
    <el-form-item prop="createdAt2">
      <el-date-picker style="width: 150px" v-model="userAddressDTO.createdAt2" type="date" placeholder="选择日期"></el-date-picker>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" size="small" >查询</el-button>
      <el-button  type="success" @click="resetForm('ruleForm')" size="small">重置</el-button>
    </el-form-item>
  </el-form>
    </el-card>
    <el-card style="height: 520px;margin-top: 5px">
      <div>
        <el-button size="small" type="danger" @click="deleteBatch" icon="el-icon-minus">批量删除</el-button>
        <el-button size="small" type="primary" @click="handleAdd" icon="el-icon-plus"> 添加</el-button>
      </div>
      <!--添加/修改弹窗-->
      <el-dialog :title="title" :close-on-click-modal="false"  style="margin-left: 300px; width: 1000px;"  :visible.sync="editUserDialog">
        <el-form :model="editUserAddress" label-width="80px"  :rules="rules" ref="editUserAddress">
          <el-form-item label="用户ID" prop="userId">
            <el-input size="small" style="width: 300px;" v-model="editUserAddress.userId" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="recipientName">
            <el-input size="small" style="width: 300px;" v-model="editUserAddress.recipientName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="recipientPhone">
            <el-input size="small" style="width: 300px;" v-model="editUserAddress.recipientPhone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地址"prop="addressDetail">
            <el-input size="small" style="width: 300px;" v-model="editUserAddress.addressDetail" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="是否启用" >
              <el-radio-group v-model="editUserAddress.isDefault">
                <el-radio label="0">否</el-radio>
                <el-radio label="1">是</el-radio>
              </el-radio-group>
          </el-form-item>
          <el-form-item label="日期" >
            <el-date-picker size="small" style="width: 300px;" v-model="editUserAddress.createdAt" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="是否异常" >
            <el-radio-group v-model="editUserAddress.anomaly">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="resetEditForm('editUserAddress')">取 消</el-button>
          <el-button size="small" type="primary" @click="saveUserAddress('editUserAddress')">确 定</el-button>
        </div>
      </el-dialog>

      <el-table
        :data="tableData"
        style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="编号" width="120px"></el-table-column>
        <el-table-column prop="userId" label="用户Id" width="120px"></el-table-column>
        <el-table-column prop="recipientName" label="姓名" width="150px"></el-table-column>
        <el-table-column prop="recipientPhone" label="手机号" width="120px"></el-table-column>
        <el-table-column prop="addressDetail" label="地址" width="120px"></el-table-column>
        <el-table-column prop="isDefault" label="是否启用" width="120px">
          <template scope="scope">
            <!-- 是否异常 1是 0否 -->
            <el-tag type="success" v-if="scope.row.isDefault === 1">是</el-tag>
            <el-tag type="danger" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createdAt"
          label="日期"
          width="120px">
        </el-table-column>
        <el-table-column prop="anomaly" label="是否异常">
          <template scope="scope">
            <!-- 是否异常 1是 0否 -->
            <el-tag type="success" v-if="scope.row.anomaly === 1">是</el-tag>
            <el-tag type="danger" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            <el-button size="mini" type="success" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination" style="display: flex;">
        <el-pagination background
                       style="display: flex; align-items: center;margin-top: 5px;margin-left: 400px;"
                       @size-change="handleSizeChange" :page-sizes="pageSizes" @current-change="handleCurrentChange"
                       :current-page="userAddressDTO.pageNum" :page-size="userAddressDTO.pageSize"
                       layout="total, sizes, prev,pager, next, jumper" :total="total">
        </el-pagination>
        <!-- 分页跳转按钮 -->
        <el-button size="small" type="primary" @click="toPage">跳转</el-button >
      </div>
    </el-card>
  </div>
</template>

<script>
import {getPageInfo, deleteOne, updateUserAddress, batchDelete, addUserAddress} from "@/api/user/useraddress";
import { title } from "@/settings";
export default {
  name: "userAddress",
  data() {
    //自定义手机号规则
    var validaterecipientPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'));
      } else {
        const reg = /^\d{11}$/;
        if(reg.test(value)){
          callback();
        }else{
          callback(new Error('请输入11位的手机号'));
        }
      }
    };
    return {
      title:"添加用户地址",
      userAddressDTO: {
        createdAt1:null,
        createdAt2:null,
        userId:null,
        recipientName:null,
        addressDetail:null,
        pageNum:1,
        pageSize:3,
      },
      editUserAddress:{},
      editUserDialog: false,
      multipleSelection:[],
      tableData: [],
      pageSizes:[3,6,9,12],
      total:0,
      rules:{
        userId: [
          { required: true, message: '请输入用户Id', trigger: 'blur' },
          { max:1, message: '请输入数字', trigger: 'blur' }
        ],
        recipientName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min:2,max:5, message: '请输入2-5个字符 ', trigger: 'blur' }
        ],
        recipientPhone: [
          { validator: validaterecipientPhone, trigger: 'blur' }
        ],
        addressDetail: [
          { required: true, message: '请输入地址', trigger: 'blur' },
          { min:3,max:10, message: '请输入5-20个字符 ', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    // 调用查询
    this.findAll();
  },
  methods: {
    async saveUserAddress(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          // 表单校验通过需要进一步判断是添加用户还是修改用户
          if (this.title === "添加用户地址") {
            addUserAddress(this.editUserAddress).then(res => {
              if (res.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '添加成功',
                  duration: 1000
                });
                this.userAddressDTO.pageNum = 1;
                  this.findAll();
                this.editUserAddress = {};
                this.$refs[formName].resetFields();
              } else {
                this.$message({
                  type: 'error',
                  message: '添加失败',
                  duration: 1000
                });
              }
            })
          } else {
            updateUserAddress(this.editUserAddress).then(res => {
              if (res.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '修改成功',
                  duration: 1000
                });
                this.userAddressDTO.pageNum = 1;
                  this.findAll();
                this.editUserAddress = {};
                this.$refs[formName].resetFields();
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败',
                  duration: 1000
                });
              }
            })
          }
          this.editUserDialog = false;
        } else {
          // 表单校验未通过
          this.$message({
            type: 'error',
            message: '表单校验失败',
            duration: 1000
          });
          return false;
        }
      });
    },
    onSubmit() {
      this.findAll()
    },
    toPage(){
      this.findAll()
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.findAll()
    },
    // 定义查询全部并分页
    findAll() {
        // 引入分页的方法
      getPageInfo(this.userAddressDTO).then(res =>{
        // 回调函数
          // 拿到res后，向表格赋值
          this.tableData = res.data.list;
          this.total = res.data.total;// 告诉我，分页数据中共有多少条
          console.log("tableData",this.tableData)
      })
    },
    //分页
    handleSizeChange(val) {
      this.userAddressDTO.pageSize = val;
      this.findAll()
    },
    handleCurrentChange(val) {
      this.userAddressDTO.pageNum = val;
      this.findAll()
    },
    //删除
    handleDelete(index, row) {
      this.$confirm("确认删除该单位吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteOne(row.id).then(res => {
          //console.log('res.code',res.code);
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          }
        })
        //刷新
        this.userAddressDTO.pageNum = 1;
          this.findAll();
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    //批量删除
    deleteBatch(){
      this.$confirm("确认删除选中项"+this.multipleSelection+"吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const ids = this.multipleSelection.join(",");
        batchDelete(ids).then(res => {
          if (res.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          }
        })
        //刷新
        this.userAddressDTO.pageNum = 1;
          this.findAll();
      }).catch(() => {
        this.$message.info("已取消删除");
      });
    },
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (const index in val) {
        this.multipleSelection.push(val[index].id);
      }
    },
    resetEditForm(formName) {
      this.$refs[formName].resetFields();
      this.editUserDialog = false;
    },
    //修改
    handleEdit(index, row) {
      this.title = "修改用户地址";
      this.editUserAddress = JSON.parse(JSON.stringify(row));
      this.editUserDialog = true;
      this.resetFields('editUserAddress')
    },
    //添加
    handleAdd() {
      this.title = "添加用户地址";
      this.editUserAddress = {};
      this.editUserDialog = true;
      this.resetFields('editUserAddress')
    },
  },
  // 就是在页面创建的时候调用这个create里面的方法
}
</script>

<style scoped>

</style>
